<template>
	<div>
		
		<basic-container>
			<avue-crud :option="tableOption" :data="gridData" :table-loading="tableLoading" :page="page" ref="crud"
				@current-change="currentPage" @size-change='sizeChange' @selection-change='selectionChange'
				v-show="isTaizhang == 0" class="management-vue">
				<template slot-scope="scope" slot="isRun">
					{{equipmentState(scope.row)}}
				</template>
				<template slot-scope="scope" slot="isMaintain">
					{{scope.row.isMaintain == 0? '是':'否'}}
				</template>
				<template slot-scope="scope" slot="isMonitor">
					{{scope.row.isMonitor == 0? '是':'否'}}
				</template>
				<template slot-scope="scope" slot="menuLeft">
					<template slot-scope="scope" slot="last_mode">
						{{scope.row.last_maintain_date}}<span>/</span>{{scope.row.last_correct_date}}<span>/</span>{{scope.row.maintain_waring}}
					</template>
				</template>
				<template slot-scope="scope" slot="menuRight">
					<el-form :inline="true" :model="searchForm" class="demo-form-inline" size="mini">

						<el-form-item label="">
							<el-input v-model="searchForm.name" placeholder="请输入设备名称"></el-input>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="searchFormSubmit()">搜索</el-button>
						</el-form-item>
					</el-form>
				</template>
				<template slot-scope="scope" slot="menu">
					<el-button type="primary" size="small" plain @click.stop="seeModeBtn(scope.row,scope.index)">导出数据
					</el-button>
				</template>
			</avue-crud>
		</basic-container>
		<!-- //新增and 修改 -->
		<el-dialog :title="modelTitle" :visible.sync="dialogTypeManageVisible" width="800px">
			<avue-form v-model="form" :option="option" ></avue-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogTypeManageVisible=false">取消</el-button>
				<el-button type="primary" @click="addSubmit">导出数据</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	import {
		option
	} from "@/const-personal/equipment/device/dashboard.js"
	import {
		getToken
	} from "@/util/auth";
	import {dateTypeSelectAll} from '../../../api/equipment/device/management.js'
	import {
		deepClone,
		equipmentTypeTreeVChildrenNull,
		getDepartmentTreeOfId,
		DepartmentTreeVChildrenNull,
		getDepartmentTreeOfValue
	} from "@/util/util.js"
	import {
		getEquipmentList,
		getWarehouseList,
		getEquipmentType,
		addEquipment,
		deleteEquipment,
		updateEquipment,
		getLaboratoryList,
		upWalk,
		downBack,
		addMaintenanceAppointment,
		addTrouble,
		addScrapApplication,
		getDevList, //设备类别
		excelWrite,
	} from '@/api/equipment/device/management.js'
	import {
		validatenull
	} from '@/util/validate'
	import website from "@/const/website";
	import {
		getUserList,
		getDepartmentList,
		getUserByRolesType,
		addUser,
		deleteRolesItem,
		updateUser,
		//部门
		addDepartment,
		updateDepartment,
		deleteDepartment,
		findByIdPicture
	} from "@/api/sysSetup/uesr.js";

	export default {
		data() {
			return {
				form: {
					datetimerange:[]
				},
				option: {
					labelWidth: 110,
					submitBtn:false,
					emptyBtn:false,
					labelPosition:'top',
					column: [{
						label: "时间日期范围",
						type: 'datetimerange',
						prop: 'datetimerange',
						format: 'yyyy-MM-dd HH:mm:ss',
						valueFormat: 'yyyy-MM-dd HH:mm:ss',
						startPlaceholder: '时间日期开始范围自定义',
						endPlaceholder: '时间日期结束范围自定义',
					}]
				},
				dialogTypeManageVisible: false,
				modelTitle: '', //设备模态标题
				newspaperStopRules: {
					type: [{
						required: true,
						message: '请选择类型',
						trigger: 'change'
					}],
					docs: [{
						required: true,
						message: '请输入申请说明',
						trigger: 'blur'
					}]
				},
				sizeForm: {
					state: '',
					maintainWaring: '',
					appointment: '',
					equipmentTypeId: '',
					location: '',
				}, //top search
				isTaizhang: 0, //台账
				typeModeAdd: false, //类型模态框添加按钮
				uploadData: {}, //上传图片附带参数
				stateMode: false, //修改状态
				stateModeBtnName: '', //启用模态框按钮名称
				stateModeTitle: '', //启用模态框名称
				stateModeForm: {}, //启用模态表单数据
				stateModeFormIs: false, //启用模态框表单启用
				typeMode: false, //类型模态框
				activeName: 0,
				is_picture_urlClass: false,
				addModel: false,
				modelTitle: '', //设备模态标题
				addForm: {
					name: '',
					coded: '',
					marking: '',
					brand: '',
					supplier: '',
					equipment_type_id: '',
					price: '',
					purchasing_date: '',
					is_maintain: -1,
					is_monitor: -1,
					radio: true,
					options: '',
					location: '',
					locations: '',
					is_run: -1,
					maintain_waring: '',
					correct_cycle: '',
					voltage_waring: '',
					electricity_waring: '',
					maintain_cycle: '',
					is_transmission: -1,
					interface_type: -1,
					equipment_site: '',
					stop_cause: '',
					mode: -1,
					pictureUrl: '',
					phoneNum: ''
				},
				//上传图片
				imageUrl: '',
				actionUrl: `${website.axiosUrl}/equipment/v1/upload`,
				uploadHeaders: {
					Authorization: getToken()
				},
				//仓库列表
				WarehouseList: [],
				LaboratoryList: [], //实验室列表
				equipmentType: [], //设备类型
				seachEquipmentType: [],
				seachEquipmentTypeIds: [],
				equipmentTypeIds: [],
				// addModelrules: sbRules,
				selectionRow: {
					id: ''
				},
				searchForm: {
					name: '',
					checked: '',
					model: '',
					coded: ''
				},
				is_update: false, //修改标识
				updateId: null,
				tableOption: option, //表格设置属性
				tableData: [], //表格的数据
				tablePage: 1,
				tableLoading: false,
				tabelObj: {},
				page: {
					total: 0, //总页数
					currentPage: 1, //当前页数
					pageSize: 10, //每页显示多少条
					pageSizes: [5, 10, 20] //
				},
				grade: {
					box: false,
					check: []
				},
				gridData: [],
				// 部门管理
				treeOption: {
					children: "children",
					label: "label"
				},
				treeData: [],
				//增加部门
				dialogFormTypeVisible: false,
				dialogFormType: {},
				rulesType: {
					parentId: [{
						required: true,
						message: "请选择部门分类",
						trigger: "change"
					}],
					content: [{
						required: true,
						message: "请输入分类",
						trigger: "blur"
					}]
				},
				// 多级联动配置
				cascaderPeops: {
					value: "id",
					label: "label"
				},
				// 修改部门标题
				dialogTypeTitleVisible: false,
				dialogTypeTitle: {
					name: "",
					parentId: []
				},
				rulesTypeTitle: {
					name: [{
						required: true,
						message: "不能为空",
						trigger: "blur"
					}],
					parentId: [{
						required: true,
						message: "不能为空",
						trigger: "change"
					}]
				},
				is_update: false, //修改标识
				getDepartmentTree: [],
				getDepartmentTreeSelect: [],
				devTypeArr: [], //数组设备类别 新
				endTime:'',
				startTime:'',
				deviceId:'',
				type:'',
				excelid:'',
				selectName:''

			}
		},
		created() {
			this._getDepartmentList(); //分类
			this.handleList();
			this._getModelSelectData();
		},
		mounted() {
           

		},
		computed: {
			//设备状态转换
			equipmentState() {
				return ((state) => {
					let result = ''
					switch (state.isRun) {
						case 0:
							result = '已启用'
							break;
						case 1:
							switch (state.stopCause) {
								case 0:
									result = '保养中'
									break;
								case 1:
									result = '校准中'
									break;
								case 2:
									result = '维修中'
									break;
								case 3:
									result = '已停用'
									break;
								case 4:
									result = '已报废'
									break;
							}
					}
					return result
				})
			},
			//预约
			appointment() {
				return ((option) => {
					let result = ''
					switch (option) {
						case 0:
							result = '可预约'
							break;
						case 1:
							result = '不可预约'
							break;
						case 2:
							result = '可借用'
							break;
						case 3:
							result = '不可借用'
							break;
					}
					return result
				})
			},
			locationList() {
				return (this.addForm.locations == 1 ? this.LaboratoryList : this.WarehouseList)
			},
			//保养 预警  校准
			calibration() {
				return ((scope) => {
					if (scope.maintainCycle && scope.correctCycle && scope.maintainWaring) {
						return (scope.maintainCycle + '/' + scope.correctCycle + '/' + scope.maintainWaring)
					} else {
						return ''
					}
				})
			},
			devTypeArr () {
			  return this.jsonToArray(this.equipmentType)
			},
			// 设备类别
			comEqType() {
				return ((type) => {
					for (let i = 0; i < this.devTypeArr.length; i++) {
						if (this.devTypeArr[i].id == type) {
							// console.log("name:" + this.equipmentType[i].label)
							return this.devTypeArr[i].name
						}
					}
				})
			},
			//存放位置
			LocationName() {
				return ((location) => {
					return location.location ? '实验室' : '仓库';

				})
			},
		},
		methods: {
			...mapMutations('equipmentLedger', ['setEquipmentLedger']),
			dateTypeSelectAllPost(){
				dateTypeSelectAll().then(res =>{
					 
				})
			},
			addSubmit(row){
				console.log("this.from: ",this.form.datetimerange.length);
				
				if(this.form.datetimerange.length == 0) return this.$message({
					message:'请选择时间范围',
					type:'warning'
				})
				
				
				let object = JSON.parse(JSON.stringify( this.form))
			
				this.endTime = object.datetimerange[1]
				this.startTime= object.datetimerange[0]
				let data = {
					endTime:this.endTime,
				    startTime:this.startTime,
					deviceId:this.deviceId,
					type: this.excelid
				}				
				this.excelWriteGet(data)
			},
			//导出数据
			seeModeBtn(row) {
				console.log(row, '---')
				let name = row.name
				this.selectName = row.name
				this.deviceId = row.deviceId ==null?'':row.deviceId
				dateTypeSelectAll().then(res =>{
					let list = res.data.data
					 for(let i=0; i<list.length; i++){
						 if(name ==list[i].dateName){
							 this.excelid = list[i].id
							 console.log("this.excelid: ",this.excelid);
						 }
					 }
				})
				
				this.dialogTypeManageVisible = true
			},
            excelWriteGet(data){
				excelWrite(data).then(res =>{
					     this.form.datetimerange=[]
						 if(res.data.byteLength ==40) return this.$message({
						 	message:'暂无该时间段数据',
						 	type:'warning'
						 })
					    // let blob = new Blob([res.data], {type: "application/vnd.ms-excel"})
					    // let objectUrl = URL.createObjectURL(blob) // 创建URL
					    // location.href = objectUrl;
					    // URL.revokeObjectURL(objectUrl); // 释放内存
						this.dialogTypeManageVisible = false
						let blob = new Blob([res.data])
						let a =  document.createElement("a")
						a.href = URL.createObjectURL(blob)
						a.download = this.selectName+'数据.xlsx'; //设置文件名
						a.style.display = "none";  // 障眼法藏起来a标签
						document.body.appendChild(a); // 将a标签追加到文档对象中
						a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
						a.remove(); // 一次性的，用完就删除a标签
				 })
			},
			_getModelSelectData() {
				getWarehouseList().then(res => { //仓库列表
					if (res.data.code === 200) {
						this.WarehouseList = res.data.data
					} else {
						this.$notify.error(res.data.message)
					}
				})
				getLaboratoryList().then(res => { //实验室列表
					if (res.data.code === 200) {
						this.LaboratoryList = res.data.data
					} else {
						this.$notify.error(res.data.message)
					}
				})
			},
			//设备类别变化
			equipmentTypeChange(val) {
				this.sizeForm.equipmentTypeId = this.equipmentTypeIds[this.equipmentTypeIds.length - 1] || null
			},
			//top  搜索
			onSearch() {
				this.handleList(this.sizeForm)
			
			},

			examineModeBtn(row, index) {
				this.examineModeType = 2;
				this.examineMode = true
			},


			//设备类别管理
			eqiupmentTypeManage() {
				this.typeMode = true
				// this.dialogTypeManageVisible = true;
			},
			//仅显示能传输数据设备
			searchFormSubmit() {
				console.log(this.searchForm);
				let data = {
					isTransmission: this.searchForm.checked ? 0 : null,
					name: this.searchForm.name,
					// equipmentCoding: this.searchForm.coded,
					coded: this.searchForm.coded, //编码
					//equipmentTypeId: this.seachEquipmentTypeId[this.seachEquipmentTypeId.length-1],
					marking: this.searchForm.model, //型号
					page: 1,
					size: this.page.pageSize
				}
				this._getList(data)
			},
			//获取设备列表数据
			handleList(search) {
				let data = {
					page: this.page.currentPage,
					size: this.page.pageSize
				};
				if (search) {
					data['page'] = 1
					switch (search.state) {
						case 0: // 已启用
							data['isRun'] = search.state //设备状态
							data['stopCause'] = null //设备状态
							break;
						case 1: // 已停用
							data['isRun'] = search.state //设备状态
							data['stopCause'] = 3 //设备状态
							break;
						case 2: // 保养中
							data['isRun'] = 1 //设备状态
							data['stopCause'] = 0 //设备状态
							break;
						case 3: // 校准中
							data['isRun'] = 1 //设备状态
							data['stopCause'] = 1 //设备状态
							break;
						case 4: // 维修中
							data['isRun'] = 1 //设备状态
							data['stopCause'] = 2 //设备状态
							break;
						case 5: // 已报废
							data['isRun'] = 1 //设备状态
							data['stopCause'] = 4 //设备状态
							break;
						default:
							break;
					}
					data['equipmentState'] = search.state //设备状态
					data['options'] = search.appointment //预约
					data['warning'] = search.maintainWaring //监控
					data['equipmentTypeId'] = this.seachEquipmentTypeIds[this.seachEquipmentTypeIds.length - 1]
					data['location'] = search.location
				}
				console.log(data);
				this._getList(data)
			},
			//获取设备列表数据 ---发请求
			_getList(data) {
				this.tableLoading = true;
				getEquipmentList(data)
					.then(res => {
						console.log(res, '---');
						if (res.data.code === 200) {
							const data = res.data.data;
							this.gridData = data.list;
							this.page.total = data.total;
							this.page.pageSize = data.pageSize
							this.page.currentPage = data.pageNum
							this.tableLoading = false;
						} else {
							this.$notify.error(res.data.message)
						}
					});
			},
			// 切换页面
			currentPage(val) {
				// console.log(val);
				this.page.currentPage = val;
				this.handleList()
			},
			sizeChange(val) {
				// console.log(val);
				this.page.pageSize = val
				this.handleList()
			},
			//上传图片成功
			handleAvatarSuccess(response, file) {
				this.is_picture_urlClass = true;
				console.log(response, file);
				if (response.code === 200) {
					this.addForm.pictureUrl = response.data
					console.log("二级:" + response.data)

					this.imageUrl = URL.createObjectURL(file.raw);
					console.log("一级:" + URL.createObjectURL(file.raw))
					this.$notify.success("图片上传成功");
				} else {
					this.$notify.error(response.message);
				}
			},
			// 图片上传失败
			uploadError(err, file) {
				this.$notify.error(err);
			},
			//上传图片前的操作
			// beforeAvatarUpload (file) {
			//   const isJPG = file.type === 'image/jpeg';
			//   const isLt2M = file.size / 1024 / 1024 < 2;
			//   if (!isJPG) {
			//     this.$notify.error('上传头像图片只能是 JPG 格式!');
			//   }
			//   if (!isLt2M) {
			//     this.$notify.error('上传头像图片大小不能超过 2MB!');
			//   }
			//   return isJPG && isLt2M;
			// },
			radioChange() {
				this.$refs['addForm'].validate((valid) => {
					return false;
				});
			},
			stateModeBtn(state) {
				// console.log(this.selectionRow.id)
				if (!this.selectionRow.id) {
					this.$notify.info('请选择你需要操作的项目')
					return;
				}
				console.log(state);
				const stateBtnName = ['启用', '停用', '提交', '提交', '提交']
				const stateTitle = ['启用确认', '停用确认', '维保申请单', '故障报停单', '报废申请单']
				this.stateMode = true;
				this.stateModeBtnName = stateBtnName[state]
				this.stateModeTitle = stateTitle[state]
				this.stateModeFormIs = state; //停用
				if (state >= 2) {
					this.newspaperStop.typeTitle = stateTitle[state].slice(0, 2) + '类型'
					this.newspaperStop.docsTitle = stateTitle[state].slice(0, 2) + '说明'
				}
			},
			selectionChange(selection) {
				console.log(selection);
				this.selectionRow = selection[selection.length - 1] || {
					id: ''
				}
			},
			// success 处理
			_successInfo(res, shenqi = false) {
				if (res.data.code === 200) {
					this.$notify.success(res.data.message)
					this.handleList();
					this.stateMode = false
					this.selectionRow = {
						id: ''
					}
					if (shenqi) {
						this.$refs['newspaperStop'].resetFields();
					}
				} else {
					this.$notify.error(res.data.message)
				}
			},
			//state confirm
			menuModeFormBtn() {
				const state = this.stateModeFormIs //操作按钮
				const {
					id
				} = this.selectionRow
				if (state === 0) { //启用
					//选择项id
					upWalk({
						id
					}).then(res => {
						this._successInfo(res)
					})
				} else if (state === 1) { //停用
					if (this.stateModeForm.stop_cause === '') {
						this.$notify.info('请选择停用类型')
						return;
					}
					let params = {
						id,
						stopCause: this.stateModeForm.stop_cause
					}
					console.log(params);
					downBack(params).then(res => this._successInfo(res))
				} else {
					this.$refs['newspaperStop'].validate(valid => {
						// console.log(v, 'v');
						if (valid) {
							if (state === 2) { //维保申请
								let params = {
									// equipmentId: id,
									// maintenanceType: this.newspaperStop.type,
									// maintenanceInstructions: this.newspaperStop.docs
									equipmentId: id,
									maintenanceType: this.newspaperStop.type,
									remakes: this.newspaperStop.docs
									// applicationTime: this.formatDate() //申请时间（取得本地时间）
								}
								console.log(params, '维保申请');
								addMaintenanceAppointment(params).then(res => this._successInfo(res, true))
							} else if (state === 3) { // 故障报停
								let params = {
									equipmentId: id,
									troubleStatus: this.newspaperStop.type,
									troubleNote: this.newspaperStop.docs
								}
								addTrouble(params).then(res => this._successInfo(res, true))
							} else if (state === 4) { //报废申请
								let params = {
									equipmentId: id,
									// scrapStatus: this.newspaperStop.type,
									scrapType: this.newspaperStop.type,
									maintenanceInstructions: this.newspaperStop.docs
								}
								addScrapApplication(params).then(res => this._successInfo(res, true))
							}
						} else {
							this.$notify.info('请填写信息')
							return false;
						}
					})
				}
			},
			// close  stateMode
			menuModeFormBtnClose() {
				this.stateMode = false
				// this.$refs['newspaperStop'].resetFields();
			},
			handleClick(tab, event) {
				if (this.activeName == '-1') {
					this.isTaizhang = 0;
				}
			},
			// 获取设备类别数据
			_getDepartmentList() {
				getDevList().then(res => {
					if (res.data.code == 200) {
						this.equipmentType = DepartmentTreeVChildrenNull(res.data.data)
						this.getDepartmentTree = DepartmentTreeVChildrenNull(res.data.data); //设备tree
						this.seachEquipmentType = DepartmentTreeVChildrenNull(res.data.data, [{
							label: '全部',
							value: ''
						}])

						this.devTypeArr = this.jsonToArray(res.data.data)
						// this.departmentOption = res.data.data;
					} else {
						this.$notify.error(res.data.message)
					}
				});
			},

			// 点击分类管理
			// typeManage() {
			// 	this.dialogTypeManageVisible = true;
			// },
			// 新增--部门管理 - 一级部门
			appendTreeType() {
				this.dialogFormTypeVisible = true;
			},
			// 新增--部门管理 - 子级部门
			addDepartment(node, data) {
				this.dialogFormType.parentId = data.value
				this.dialogFormTypeVisible = true;
			},
			//   点击树
			handleNodeClick(data) {
				// console.log(data);
			},
			// 修改标题--部门管理
			editTree(node, data) {
				this.dialogTypeTitle.name = data.label
				this.dialogTypeTitle.id = data.id
				this.dialogTypeTitle.parentId = getDepartmentTreeOfValue(this.getDepartmentTree, data.id)
				this.dialogTypeTitleVisible = true;
			},

		}
	}
</script>

<style lang="scss" scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409eff;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.default-head {
		font-size: 120px;
		border: 1px solid #606266;
		border-radius: 5px;
		padding: 30px 30px;
	}

	.avue-crud__menu {
		min-height: 0px;
		margin-bottom: 0px;
	}

	.el-row {
		margin-left: 20px !important;
		margin-bottom: 20px;

		.el-col-3 {
			font-weight: 600;
		}
	}

	.lineDiv {
		border-top: 1px solid #d6d6d6;
		margin: 0px 1% 20px 25px;
		width: 90%;
	}

	.el-dialog__body {
		padding-top: 15px;
		padding-bottom: 0px;
	}
</style>

<style lang="scss">
	.zindex1>.el-form-item__content {
		z-index: -1;
	}

	.picture_url {
		min-height: 175px;
	}

	.picture_urlClass div[class~="el-upload"] {
		display: none;
	}

	.custom-tree-node {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 8px;
	}

	thead .el-checkbox__inner {
		display: none !important;
	}
</style>
